package com.atguigu.gulimall.ware.listener;


import com.atguigu.common.to.mq.MqMessage;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.MqMessageService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * 自动解锁库存
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
@Slf4j
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @Autowired
    MqMessageService mqMessageService;


    /**
     * 1、库存自动解锁
     *      下单成功，库存锁定成功，后续业务失败， 导致订单回滚， 这时 库存就要解锁
     * 2、订单失败
     *      库存锁定失败
     *      只要解锁库存的消息失败，一定要告诉服务解锁失败
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        log.info("******时间到，自动解锁，收到解锁库存的信息******");
        try {
            // 解锁 库存
            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            String string = new String(message.getBody());
            System.out.println("记录MQ 的日志 , string=" + string);
            MqMessage mqMessage = new MqMessage();
            mqMessage.setMessageId(to.getMqMessageId());
            mqMessage.setMessageStatus(3);  // 已抵达
            mqMessage.setUpdateTime(new Date());
            mqMessageService.updateById(mqMessage);
        }catch (Exception e) {
            e.printStackTrace();
            // 解锁失败  , 消息重新放回 队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }



    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Channel channel, Message message) throws IOException {
        log.info("订单取消成功， 开始解锁库存。。。");
        try{
            wareSkuService.unLockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            String string = new String(message.getBody());
            System.out.println("记录MQ 的日志 , string=" + string);
            MqMessage mqMessage = new MqMessage();
            mqMessage.setMessageId(orderTo.getMqMessageId());
            mqMessage.setMessageStatus(3);  // 已抵达
            mqMessage.setUpdateTime(new Date());
            mqMessageService.updateById(mqMessage);
        }catch (Exception e){
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
